<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Renting;
use App\services\Curl;
use App\services\JwtService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TokenController extends BaseController
{


    /*
     * 高版本 不支持 getuserinfo  获取不到头像
     */
    public function generateToken(Request $request){
        $params =$this->validateParams($request->all(),[
            'code'=>'required'

        ]);

        //校验参数



       //通过code 获取微信端 session_key 和 appid
        $res= (new Curl())->getUrl(sprintf(config('wx.getUrl'),config('wx.appid'),config('wx.secret'),$params['code']));


        //判断链接是否成功
        if(isset($res['errcode']) && $res['errcode'] != 0){


            return $this->writeJson(0,'',"获取openid失败");
        }


        //判断openid是否存在
       $renting= Renting::where('openid',$res['openid'])->first();
        if ($renting){
            //更新session_key
            $renting->session_key =$res['session_key'];
            $renting->save();
        }else{
            //如果没有该账号 进行注册
            $renting=  Renting::create($res);

        }

        //生成token 并返回
       $token =(new JwtService())->encode($renting);

        return $this->writeJson(0,['token'=>$token],'获取成功');
    }
}
